package gr.handmademarket.bl.operations;

import gr.handmademarket.hibernate.HibernateUtil;
import gr.handmademarket.po.implementations.KeyGenerator;
import gr.handmademarket.po.implementations.ProductCategory;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * operation that saves a category.
 */
public class CreateCategoryOperation {

	/**
	 * fetching key value of categories.
	 */
	@SuppressWarnings("nls")
	private static final String hqlString = 
			"select kg from KeyGenerator kg where kg.tableName = :entityName";
	
	/**
	 * the category.
	 */
	private ProductCategory category;
	
	/**
	 * Creates a new CreateCategoryOperation object. 
	 *
	 */
	public CreateCategoryOperation() {
		// empty
	}
	
	/**
	 * execution method.
	 */
	@SuppressWarnings("nls")
	public void execute(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery(hqlString);
		query.setString("entityName", "categories");
		KeyGenerator keyGen = (KeyGenerator) query.list().get(0);
		Integer nextVal = keyGen.getKeyValue() + 1;
		category.setCode(nextVal);
		keyGen.setKeyValue(nextVal);
        session.save(category);
        session.update(keyGen);
        session.getTransaction().commit();
	}

	/**
	 * @return persisted category.
	 */
	public ProductCategory getCategory() {
		return category;
	}

	/**
	 * @param category
	 */
	public void setCategory(ProductCategory category) {
		this.category = category;
	}

}
